package com.hjms.common.entity.exception;

import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.nio.charset.Charset;
import  com.alibaba.fastjson.JSON;

/**
 * @author 何杨谊
 * @description: TODO
 * @date 2023/2/8 14:57
 */
@Slf4j
public class OpenFeignErrorDecoder implements ErrorDecoder {
    /**
     * 重写Feign异常解析
     *
     * @param s
     * @param response
     * @return
     */
    @Override
    public Exception decode(String s, Response response) {
        String body = "";
        try {
            body = Util.toString(response.body().asReader(Charset.defaultCharset()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        ErrorResult result = null;
        if (body != "") {
            int status = response.status();
            if (status == 412) {
                result = JSON.parseObject(body, ErrorResult.class);
                return new Precondition412Exception(result.getCode(), result.getMessage());
            }
        }
        return new RuntimeException(body);
    }
}
